package com.zerui.manager.app.device.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.zerui.cola.dto.PageResponse;
import com.zerui.devicemanager.provider.DeviceDubboService;
import com.zerui.devicemanager.provider.cmd.DeviceNodePageCmd;
import com.zerui.devicemanager.provider.dto.DeviceDTO;
import com.zerui.manager.app.devicegroup.convertor.DeviceVoConvert;
import com.zerui.manager.devciecurfewtimelog.gateway.DeviceCurfewtimeLogGateWay;
import com.zerui.manager.device.Device;
import com.zerui.manager.device.domainservice.DeviceRepository;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import com.zerui.manager.web.cmd.DeviceInfoCmd;
import com.zerui.manager.web.vo.DevicePageVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-23 13:53
 */
@Component
@CatchAndLog
public class DeviceQryCmdExe {

    @DubboReference
    private DeviceDubboService deviceDubboService;

    @Value("${spring.application.name}")
    private String applicationName;

    @Resource
    private DeviceGroupRepository deviceGroupRepository;
    @Resource
    private DeviceRepository deviceRepository;


    public PageResponse<DevicePageVO> execute(DeviceInfoCmd deviceInfoCmd) {
        Set<String> deviceIds = null;
        if(ObjectUtils.isNotEmpty(deviceInfoCmd.getOrgId())){
            DeviceGroup deviceGroup = deviceGroupRepository.selectById(deviceInfoCmd.getOrgId());
            if(ObjectUtils.isNotEmpty(deviceGroup)){
                deviceIds = deviceGroup.getDeviceIds();
                if(!"根节点".equals(deviceGroup.getOrgName()) && CollectionUtils.isEmpty(deviceIds)){
                    return PageResponse.of(
                            deviceInfoCmd.getPageSize(),
                            deviceInfoCmd.getPageIndex());
                }
            }
        }
        PageResponse<DeviceDTO> pageDeviceList = deviceDubboService.getPageDevcieList(
                createDeviceNodePageCmd(
                        deviceInfoCmd,
                        deviceIds
                )
        );
        List<DevicePageVO> devicePages = DeviceVoConvert.INSTANCE.covertDeviceDTOToPageVO(pageDeviceList.getData());
        if(CollectionUtils.isNotEmpty(devicePages)){
			//获取 门禁数据库数据
            Set<Long> deviceList = devicePages.stream().map(DevicePageVO::getDeviceId).collect(Collectors.toSet());
            List<Device> devices = deviceRepository.selectByDeviceIds(deviceList);
            Map<Long, Device> deviceMap = new HashMap<>(16);
            if(CollectionUtils.isNotEmpty(devices)){
                deviceMap = devices.stream().collect(Collectors.toMap(Device::getDeviceId, e -> e));
            }
            Map<Long,DeviceGroup> deviceGroupMap = deviceGroupRepository.getDeviceGroupMapByIds(deviceList);

	        //添加vo 数据字段 定时任务数据
            for (DevicePageVO vo:devicePages){
                vo.setEnableStatus(0);
                if(deviceMap.containsKey(vo.getDeviceId())){
                    Device device = deviceMap.get(vo.getDeviceId());
                    vo.setEnableStatus(device.getEnableStatus());
                    vo.setAccess(device.getAccess());
                    vo.setStartTime(device.getStartTime());
                    vo.setEndTime(device.getEndTime());
                    vo.setTimedTaskStatus(device.getTimedTaskStatus());
                    vo.setCurfewStatus(device.getCurfewStatus());
                }
                if(deviceGroupMap.containsKey(vo.getDeviceId())){
                    DeviceGroup deviceGroup = deviceGroupMap.get(vo.getDeviceId());
                    vo.setGroupName(deviceGroup.getOrgName());
                    vo.setOrgId(deviceGroup.getId());
                }
            }

            return PageResponse.of(
		            devicePages,
		            pageDeviceList.getTotalCount(),
		            pageDeviceList.getPageSize(),
		            pageDeviceList.getPageIndex()
            );
        }
        return PageResponse.of(
                deviceInfoCmd.getPageSize(),
                deviceInfoCmd.getPageIndex()
        );
    }



    private DeviceNodePageCmd createDeviceNodePageCmd(DeviceInfoCmd deviceInfoDto,Set<String> deviceIds) {

        DeviceNodePageCmd cmd = new DeviceNodePageCmd();
        cmd.setBizUnit(applicationName);
        cmd.setDeviceIds(CollectionUtils.isEmpty(deviceIds) ? null :
		        deviceIds.stream().
				        map(Long::parseLong).
				        collect(Collectors.toList())
        );
        cmd.setPageIndex(deviceInfoDto.getPageIndex());
        cmd.setPageSize(deviceInfoDto.getPageSize());
        cmd.setName(deviceInfoDto.getName());
        cmd.setPositionCmd(deviceInfoDto.getPositionCmd());
        cmd.setCode(deviceInfoDto.getCode());
        cmd.setStatus(deviceInfoDto.getStatus());
        cmd.setType(deviceInfoDto.getType());
        return cmd;

    }
}
